import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { Shop, PaginatedResponse } from '../../types';

interface ShopState {
  shops: Shop[];
  currentShop: Shop | null;
  total: number;
  loading: boolean;
  error: string | null;
  searchKeyword: string;
  filters: {
    status?: string;
    ownerId?: string;
  };
  pagination: {
    page: number;
    limit: number;
  };
}

const initialState: ShopState = {
  shops: [],
  currentShop: null,
  total: 0,
  loading: false,
  error: null,
  searchKeyword: '',
  filters: {},
  pagination: {
    page: 1,
    limit: 20,
  },
};

export const fetchShops = createAsyncThunk(
  'shop/fetchShops',
  async (params: any, { rejectWithValue }) => {
    try {
      return { data: [], total: 0 } as PaginatedResponse<Shop>;
    } catch (error: any) {
      return rejectWithValue(error.message || '获取店铺列表失败');
    }
  }
);

const shopSlice = createSlice({
  name: 'shop',
  initialState,
  reducers: {
    setSearchKeyword: (state, action) => {
      state.searchKeyword = action.payload;
    },
    setFilters: (state, action) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    setPagination: (state, action) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchShops.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchShops.fulfilled, (state, action) => {
        state.loading = false;
        state.shops = action.payload.data;
        state.total = action.payload.total;
      })
      .addCase(fetchShops.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { setSearchKeyword, setFilters, setPagination, clearError } = shopSlice.actions;
export default shopSlice.reducer;
